package com.augn.service.impl;

import com.augn.entity.GoodsEvaluateMain;
import com.augn.entity.Result;
import com.augn.mapper.GoodsEvaluateMainMapper;
import com.augn.service.IGoodsEvaluateMainService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author augn
 * @since 2022-09-22
 */
@Service
public class GoodsEvaluateMainServiceImpl extends ServiceImpl<GoodsEvaluateMainMapper, GoodsEvaluateMain> implements IGoodsEvaluateMainService {

    @Autowired
    private GoodsEvaluateMainMapper mapper;

    // 新增一个商品主评价
    @Override
    public Result<?> insertOneGoodsEvaluateMain(GoodsEvaluateMain goodsEvaluateMain) {
        int insert = mapper.insert(goodsEvaluateMain);
        if(insert==0){
            return Result.error("-1","新增失败");
        } else{
            return Result.success(insert);
        }
    }

    //删除一个商品主评价
    @Override
    public Result<?> deleteOneGoodsEvaluateMain(Integer id) {
        int delete = mapper.deleteById(id);
        if(delete==0){
            return Result.error("-1","删除失败");
        } else{
            return Result.success(delete);
        }
    }

    // 获取一个主评价及完整的全部从评价
    @Override
    public Result<?> getOneGoodsEvaluate(Integer id){
        GoodsEvaluateMain goodsEvaluate = mapper.getOneGoodsEvaluate(id);
        if(goodsEvaluate==null){
            return Result.error("-1","无此主评价·");
        } else {
            return Result.success(goodsEvaluate);
        }
    }

    // 分页查询一个商品的主评价以及主评价的从评价数量
    @Override
    public Result<?> getPartGoodsEvaluate(Integer id, Integer pageNum, Integer pageSize) {

        List<GoodsEvaluateMain> goodsEvaluate;
        Map<String,Object> ret = new HashMap<>();
        QueryWrapper<GoodsEvaluateMain> wrapper= new QueryWrapper<>();

        if (pageSize == null) {
            pageSize = 20;
        }
        if(pageNum==0||pageNum==1){
            pageNum = 0;
        } else {
            pageNum=(pageNum-1)*pageSize;
        }

        goodsEvaluate = mapper.getPartGoodsEvaluate(id, pageNum, pageSize);

        wrapper.eq("goods_id",id);
        Long total = mapper.selectCount(wrapper);
        ret.put("evaMainList",goodsEvaluate);
        ret.put("pages",total/pageSize==0?1:total/pageSize);
        ret.put("total",total);

        if (goodsEvaluate.isEmpty()) {
            return Result.error("-1", "该商品暂无评论");
        } else {
            return Result.success(ret);
        }
    }
}
